import {Button, Form, message, Modal, Space, Switch} from "antd";
import React, {useEffect, useState} from "react";
import {useModel} from "@@/exports";
import CustomSelect from "@/pages/components/CustomSelect";
import {ActionType} from "@ant-design/pro-components";
import {
  addWorkSheetPreserveUsingPOST,
  editWorkSheetPreserveUsingPUT
} from "@/services/model/workSheetPreserveController";
import {
  getProductCodeByWsSerialIdFromWorksheetYieldUsingGET,
  listProductCodeFromWorksheetYieldUsingGET,
  listWsSerialNumberFromWorksheetYieldUsingGET
} from "@/services/model/worksheetYieldInfoController";

type ModelProps = {
  saveType: string,
  isModalOpen: boolean,
  onCancel: () => void,
  initProductCode: string,
  initWorkOrderNo: string,
  editRecord: API.WorkSheetPreserveDTO,
  actionRef: React.MutableRefObject<ActionType | undefined>,
}

const layoutStyle = {
  labelCol: {span: 6},
  wrapperCol: {span: 16},
};
const tailLayout = {
  wrapperCol: {offset: 8, span: 16},
};

const AddOrEditModel: React.FC<ModelProps> = ({
                                                saveType,
                                                isModalOpen,
                                                onCancel,
                                                initProductCode,
                                                initWorkOrderNo,
                                                editRecord,
                                                actionRef
                                              }) => {
  const [selectProductCode, setSelectProductCode] = useState('');
  const [selectWorkOrderNo, setSelectWorkOrderNo] = useState('');
  const [editSwitch, setEditSwitch] = useState(false);
  const [addAndEditForm] = Form.useForm();

  // useEffect(() => {
  //   setSelectProductCode(initProductCode);
  //   setSelectWorkOrderNo(initWorkOrderNo);
  //   addAndEditForm.setFieldsValue(editRecord);
  //   setEditSwitch(editRecord.hidden === 1)
  // }, [initProductCode, initWorkOrderNo, isModalOpen])
  // 替换为 --->
  const [prevItems, setPrevItems] = useState(isModalOpen);
  if (isModalOpen !== prevItems) {
    setPrevItems(isModalOpen);
    setSelectProductCode(initProductCode);
    setSelectWorkOrderNo(initWorkOrderNo);
    addAndEditForm.setFieldsValue(editRecord);
    setEditSwitch(editRecord.hidden === 1)
  }

  const {initialState} = useModel('@@initialState');

  const [productCodeList, setProductCodeList] = useState<{
    id: string | undefined,
    name: string | undefined
  }[]>([]);
  const [workOrderNoList, setWorkOrderNoList] = useState<{
    id: number | undefined,
    name: number | undefined
  }[]>([]);
  useEffect(() => {
    listProductCodeFromWorksheetYieldUsingGET().then((result) => {
      if (result.code === 0 && result.data) {
        const dataCodeList = result.data.filter((item: any) => item).map((item: any) => {
          return {
            id: item,
            name: item,
          }
        })
        setProductCodeList(dataCodeList);
      }
    });
  }, []);
  useEffect(() => {
    listWsSerialNumberFromWorksheetYieldUsingGET({
      productCode: selectProductCode,
    }).then((result) => {
      if (result.code === 0 && result.data) {
        const dataList = result.data.filter((item: any) => item).map((item: any) => {
          return {
            id: item.wsSerialNumber,
            name: item.wsSerialNumber,
          }
        })
        setWorkOrderNoList(dataList);
      }
    });
  }, [selectProductCode])

  const onSave = async (value: any) => {
    const newWorkSheetPreserve: API.AddWorkSheetPreserveQuery = {
      currentUserId: initialState?.currentUser?.id,
      hidden: value.hidden ? 1 : 0,
      wsSerialNumber: selectWorkOrderNo,
      productCode: selectProductCode,
    };
    const result = await addWorkSheetPreserveUsingPOST(newWorkSheetPreserve);
    if (result.code === 0 && result.data) {
      message.success('添加成功');
      onCancel();
    } else {
      message.warning(result.message);
    }
    actionRef.current?.reload();
  };
  const onEdit = async (value: any) => {
    const newWorkSheetPreserve: API.EditWorkSheetPreserveQuery = {
      id: value.id,
      currentUserId: initialState?.currentUser?.id,
      hidden: value.hidden ? 1 : 0,
      wsSerialNumber: selectWorkOrderNo,
      productCode: selectProductCode,
    };
    const result = await editWorkSheetPreserveUsingPUT(newWorkSheetPreserve);

    if (result.code === 0 && result.data) {
      message.success('修改成功');
      onCancel();
    } else {
      message.warning(result.message);
    }
    actionRef.current?.reload();
  };
  const onReset = () => {
    setSelectProductCode('');
    setSelectWorkOrderNo('')
    setEditSwitch(false);
    addAndEditForm.resetFields();
  };

  return (
    <>
      <Modal title={saveType === 'edit' ? '修改工单维护信息' : '新增工单维护信息'} open={isModalOpen}
             onCancel={onCancel}
             footer={false}>
        <Form
          name="basic"
          form={addAndEditForm}
          {...layoutStyle}
          style={{maxWidth: 500}}
          onFinish={saveType === 'edit' ? onEdit : onSave}
        >
          <Form.Item
            label="id"
            key='id'
            name='id'
            hidden={true}
          >
          </Form.Item>
          <Form.Item
            label="产品代码"
            key='productCode'
            name='productCode'
          >
            <CustomSelect name={''} selectDate={selectProductCode} datalist={productCodeList} setSelectData={(value) => {
              setSelectProductCode(value);
              setSelectWorkOrderNo('')
            }}/>

          </Form.Item>
          <Form.Item
            label="工单号"
            key='wsSerialNumber'
            name='wsSerialNumber'
          >
            <CustomSelect name={''} selectDate={selectWorkOrderNo} datalist={workOrderNoList}
                          setSelectData={(value) => {
                            setSelectWorkOrderNo(value);
                            getProductCodeByWsSerialIdFromWorksheetYieldUsingGET({
                              wsSerialNumber: value,
                            }).then((result) => {
                              if (result.code === 0 && result.data) {
                                setSelectProductCode(result.data)
                              }
                            });
                          }}/>
          </Form.Item>
          <Form.Item label="是否隐藏" key='hidden' name='hidden' valuePropName="value">
            <Switch checked={editSwitch} onChange={(value) => setEditSwitch(value)}/>
          </Form.Item>

          <Form.Item {...tailLayout} key="submit&reset">
            <Space>
              <Button type="primary" htmlType="submit" key="submit">
                提交
              </Button>
              <Button disabled={saveType === 'edit'} htmlType="button" onClick={onReset} key="reset">
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default AddOrEditModel;



